package com.yeskery.nut.extend.mybatisflex;

import com.mybatisflex.core.datasource.FlexDataSource;
import com.mybatisflex.core.mybatis.FlexConfiguration;
import com.mybatisflex.core.mybatis.FlexSqlSessionFactoryBuilder;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.extend.mybatis.BaseMyBatisPlugin;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;

import javax.sql.DataSource;

/**
 * MybatisFlex插件
 * @author Yeskery
 * 2023/7/21
 */
public class MybatisFlexPlugin extends BaseMyBatisPlugin {

    /**
     * 构建基于注解的MyBatis-Plus插件
     * @param basePackages 要扫描的基础包路径数组
     */
    public MybatisFlexPlugin(String... basePackages) {
        super(new FlexSqlSessionFactoryBuilder().build(new FlexConfiguration(new Environment("default",
                new ManagedTransactionFactory(), new EmptyDataSource()))));
        setMyBatisScanBasePackages(basePackages);
    }

    /**
     * 构建基于注解的MyBatis-Plus插件
     * @param basePackages 要扫描的基础包数组
     * @param dataSource 数据源
     */
    public MybatisFlexPlugin(String[] basePackages, DataSource dataSource) {
        super(new FlexSqlSessionFactoryBuilder().build(new FlexConfiguration(new Environment("default",
                new ManagedTransactionFactory(), new EmptyDataSource()))), dataSource);
        setMyBatisScanBasePackages(basePackages);
    }

    @Override
    protected DataSource warpDataSource(DataSource dataSource) {
        return new FlexDataSource("default", dataSource);
    }

    /**
     * 设置MyBatis扫描的基础路径
     * @param basePackages MyBatis扫描的基础路径
     */
    private void setMyBatisScanBasePackages(String[] basePackages) {
        if (basePackages == null || basePackages.length == 0) {
            throw new NutException("MyBatis Mapper Base Package Must Not Be Empty.");
        }
        Configuration configuration = getConfiguration();
        for (String basePackage : basePackages) {
            configuration.addMappers(basePackage);
        }
    }
}
